<?php

namespace app\api\controller;

use app\api\model\Channel;
use app\api\model\Pull;
use app\api\model\WxToken;
use think\cache\driver\Memcached;
use think\Controller;
use think\Db;
use think\Xiaocx;

class Login extends Controller
{

    /**
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 用户进入登陆
     */
    public function login()
    {
        $code = input('get.code');
        $share_user_id = input('get.share_user_id'); //分享者ID
//        $channel_id = input('get.channel_id');
        if (!$code) {
            json_fail('获取code失败');
        }
        //请求微信接口
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . config('xiaocx_app_id') . '&secret=' . config('xiaocx_app_secret') . '&js_code=' . $code . '&grant_type=authorization_code';
        $info = http_curl($url, 'get');

        if (isset($info['errcode'])) {
            json_fail($info['errmsg']);
        }
        if (!empty($info['openid'])) {

            //实例化数据库
            $user = new \app\api\model\User();
//            $channel = new Channel();

            //查询有无数据
            $userDetail = $user->field('id')->where(array('openid' => $info['openid'], 'status' => 1))->order('id asc')->find();
            if (!$userDetail) {
                //存储
                $userId = $user->insertGetId(array('openid' => $info['openid'], 'create_time' => time()));
                //如果渠道ID存在 就存记录表
//                if ($channel_id) {
//                    //渠道引流人数+1
//                    $channel->add_total_user_count($channel_id);
//                    $user->where(array('id' => $userId))->update(array('source_type' => 3, 'source_id' => $channel_id));
//                }
                if ($share_user_id) {
                    $share_user_id = decode($share_user_id);

                    //用户拉新表
                    $Pull=new Pull();
                    $save=array(
                        'share_user_id'=>$share_user_id,
                        'user_id'=>$userId,
                    );
                    $Pull->data($save);
                    $Pull->save();
                    $user->where(array('id' => $userId))->update(array('source_type' => 2, 'source_id' => $share_user_id));
                    //分享者引流人数+1
                    $user->where(array('id' => $share_user_id))->setInc('drainage_count', 1);
                }
            } else {
                $userId = $userDetail['id'];
            }

            // 返回用户ID
            json_success(encode($userId));
        }
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取用户信息
     */
    public function get_user_info()
    {
        //实例化数据库
        $user_id = input('post.user_id');
        if (!$user_id) {
            json_fail('获取用户id失败');
        }
        $user_id = decode($user_id);

        //实例化数据库
        $user = new \app\api\model\User();
        //查询用户信息
        $userInfo = $user->where(array('id' => $user_id))->field('id,mobile,is_vip,vip_end_time,nickname,gender,avatar_url,authorization,real_name')->find();
        
        if (!$userInfo) {
            json_success([]);
        }
        // 过期操作
        if($userInfo['vip_end_time']<time() && $userInfo['is_vip']==1) {
            Db('User')->where(array('id' => $userInfo['id']))->update(['is_vip'=>2]);
        } elseif($userInfo['vip_end_time']>time() && $userInfo['is_vip']==2) {
            Db('User')->where(array('id' => $userInfo['id']))->update(['is_vip'=>1]);
        }
        if ($userInfo['authorization'] == 1) {
            $userInfo['nickname'] = base64_decode($userInfo['nickname']);
        }
        // 返回数据
        json_success($userInfo);
    }


    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 小程序端获取用户信息并存储
     */
    public function getWechatUserInfo()
    {
        $userId = input('post.user_id');
        $nickname = input('nickName');
        $gender = input('post.gender');
        $language = input('post.language');
        $city = input('post.city');
        $province = input('post.province');
        $country = input('post.country');
        $avatar_url = input('post.avatarUrl');

        if (!$userId) {
            json_fail('获取用户id错误');
        }
        if (!$nickname) {
            json_fail('获取用户昵称错误');
        }
        if (!$avatar_url) {
            json_fail('获取用户头像错误');
        }
        $user_id = decode($userId);


        //实例化数据库
        $user = new \app\api\model\User();
        //要存储的数据
        $saveData = array(
            'nickname' => base64_encode($nickname), //昵称
            'gender' => $gender,    //性别
            'language' => $language,   //语言
            'city' => $city,            //城市
            'province' => $province,        //省
            'country' => $country,          //国家
            'avatar_url' => $avatar_url,   //头像
            'timestamp' => time(),   //授权时间
            'authorization' => 1,     //修改授权状态 为已授权 1
            'old_nickname' => $nickname  //不加密的昵称 
        );
        //存储
        $user->where(array('id' => $user_id))->update($saveData);
        $info = $this->getUserInfo($user_id);
        json_success($info);
    }

    /**
     * @param $user_id
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *  获取用户信息
     */
    public function getUserInfo($user_id)
    {
        //查询用户信息
        $userInfo = Db('User')->where(array('id' => $user_id))->find();
        if (!$userInfo) {
            return [];
        }
        return $userInfo;
    }



    /**
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取微信用户手机号码
     */
    public function get_user_wechat_phone()
    {
        // 获取code
        $code = input('post.code');
        if (!$code) {
            json_fail('获取code失败');
        }

        $userId = input('post.user_id');
        if (!$userId) {
            json_fail('用户ID不存在！');
        }
        $userId = decode($userId);

        // 获取数据
        $encryptedData = input('post.encrypt_data');
        if (!$encryptedData) {
            json_fail('获取encryptedData失败');
        }

        // 获取iv
        $iv = input('post.iv');
        if (!$iv) {
            json_fail('获取iv失败');
        }
        $iv = urldecode($iv);

        // 获取小程序ID
        $appid = Config('xiaocx_app_id');

        //请求微信接口
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . Config('xiaocx_app_secret') . '&js_code=' . $code . '&grant_type=authorization_code';
        $wechat = http_curl($url, 'get');
        if ($wechat) {
            // 初始化解密
            $xiaocx = new Xiaocx();

            $xiaocx->setConfig($appid, $wechat['session_key']);
            $data = [];

            // 判断是否解析失败
            $errCode = $xiaocx->decryptData($encryptedData, $iv, $data);
            if ($errCode == 0) {
                $res = json_decode($data, true);
                // 获取手机号码
                $mobile = $res['phoneNumber'];

                //实例化数据库
                $User = new \app\api\model\User();

                // 判断用户是否做关联
                $m_data = [
                    'mobile' => $mobile,
                    'is_bind_mobile' => 1,
                    'bind_mobile_time' => time()
                ];
                $info = $User->where(array('id'=>$userId))->update($m_data);

                if($info === false){
                    json_fail('绑定失败');
                }
                //渠道绑定手机人数维护
                $this->add_bind_mobile_count($userId);

                json_success('绑定成功');
            } else {
                json_fail($errCode);
            }
        } else {
            json_fail('获取微信服务器API接口错误！');
        }
    }


    /**
     * 定时器维护token
     */
    public function token(){
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".config('xiaocx_app_id')."&secret=".config('xiaocx_app_secret');
        $info = http_curl($url,'get');
        if(!$info){
            json_fail('获取token失败');
        }

        //实例化数据库
        $wx_token = new WxToken();

        //查询
        $infoList = $wx_token->where(array('wxatid'=> config('xiaocx_app_id') ))->value('access_token');
        if($infoList){
            //更新的数据
            $data = array(
                'access_token' => $info['access_token'],
                'expires_in' => $info['expires_in'],
                'updatetime' => date('Y-m-d H:i:s')
            );
            $wx_token->where(array('wxatid'=> config('xiaocx_app_id') ))->update($data);
        }else {
            //添加的数据
            $data = array(
            	'wxatid' => config('xiaocx_app_id'),
                'access_token' => $info['access_token'],
                'expires_in' => $info['expires_in'],
                'createtime' => date('Y-m-d H:i:s'),
                'updatetime' => date('Y-m-d H:i:s')
            );
            $wx_token->insertGetId($data);
        }
    }

}
